/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { BaseChecker, BaseMetaData } from '../BaseChecker';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { Defects, IssueReport, MatcherTypes, Rule, StmtMatcher, StmtMatcherCallback } from '../../Index';
import {
    ArkAssignStmt,
    ArkInstanceFieldRef,
    ArkInvokeStmt,
    ArkMethod,
    ClassSignature,
    ClassType,
    FunctionType,
    Stmt
} from 'arkanalyzer';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'TabsOnChangeCheck');
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/tabs-on-change-check.md',
    description: 'Prefer onAnimationStart over onChange to avoid delayed effects.'
};

const tabOnChangeSignature = '@ohosSdk/component/tabs.d.ts: TabsAttribute.onChange(@ohosSdk/component/common.d.ts: Callback<number,void>)';

export class TabsOnChangeCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private stmtMatcher: StmtMatcher = {
        matcherType: MatcherTypes.STMT,
        match(stmt: Stmt): boolean {
            return stmt instanceof ArkInvokeStmt && stmt.getInvokeExpr().getMethodSignature().toString() === tabOnChangeSignature;
        }
    };

    public registerMatchers(): StmtMatcherCallback[] {
        const matchMethodCb: StmtMatcherCallback = {
            matcher: this.stmtMatcher,
            callback: this.check
        };
        return [matchMethodCb];
    }

    public check = (stmt: Stmt): void => {
        const type = stmt.getInvokeExpr()?.getArg(0)?.getType();
        if (type instanceof FunctionType) {
            const arkClass = stmt.getCfg().getDeclaringMethod().getDeclaringArkClass();
            const method = arkClass.getDeclaringArkFile().getScene().getMethod(type.getMethodSignature());
            this.checkStateBeAssigned(method, arkClass.getSignature());
        }
    };

    private checkStateBeAssigned(method: ArkMethod | null, stateClass: ClassSignature): void {
        if (!method) {
            return;
        }
        const stmts = method.getCfg()?.getStmts();
        if (!stmts) {
            return;
        }
        for (const s of stmts) {
            if (s instanceof ArkAssignStmt && s.getLeftOp() instanceof ArkInstanceFieldRef) {
                const type = (s.getLeftOp() as ArkInstanceFieldRef).getBase().getType();
                if (type instanceof ClassType && type.getClassSignature() === stateClass) {
                    this.reportIssue(s);
                }
            }
        }
    }

    private reportIssue(stmt: Stmt): void {
        const filePath = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile().getFilePath();
        let fullPosition = stmt.getOperandOriginalPosition(0);
        if (!fullPosition) {
            return;
        }
        let lineNum = fullPosition.getFirstLine();
        let startColumn = fullPosition.getFirstCol();
        let endColumn = fullPosition.getLastCol();
        if (lineNum === -1 || startColumn === -1 || endColumn === -1) {
            return;
        }
        const severity = this.rule.alert ?? this.metaData.severity;
        let defects = new Defects(lineNum, startColumn, endColumn, this.metaData.description, severity,
            this.rule.ruleId, filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}